<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="google" content="notranslate" />
  <title>Instant Messaging</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f2f2f2;
    }

    .container {
      width: 400px;
      margin: 0 auto;
      margin-top: 100px;
      background-color: #fff;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .container h2 {
      text-align: center;
      margin-bottom: 20px;
    }

    .container input[type="text"] {
      width: calc(100% - 22px);
      padding: 10px;
      margin-bottom: 10px;
      border: 1px solid #ccc;
      border-radius: 3px;
    }

    .container input[type="submit"] {
      width: 100%;
      padding: 10px;
      background-color: #4CAF50;
      color: #fff;
      border: none;
      border-radius: 3px;
      cursor: pointer;
    }

    .container input[type="submit"]:hover {
      background-color: #45a049;
    }

    .messages {
      height: 200px;
      overflow-y: scroll;
      border: 1px solid #ccc;
      padding: 10px;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>Instant Messaging</h2>
    <div class="messages" id="messages">
        
    </div>
    <form id="messageForm">
      <input type="text" id="message" placeholder="Type your message..." required>
      <input type="submit" value="Send">
    </form>
  </div>
  <script src="websoket客户端文件.js"></script>
  <script>
    
    function init() {
        socket.onmessage = function(e) {
        let data = JSON.parse(e.data);
        var messages = document.getElementById('messages');
        var newMessage = document.createElement('div');
        var timer = document.createElement("div")
        timer.innerText = data.time;
        newMessage.innerText = data.content;
        timer.style.textAlign = 'center';
        if(data.username == localStorage.getItem("username")){
            //向右
            newMessage.style.textAlign = 'right';
        }else{
            //向左
            newMessage.style.textAlign = 'left';
        }
        newMessage.style.marginBottom = '10px';
        messages.appendChild(timer)
        messages.appendChild(newMessage);
        document.getElementById('message').value = '';
      }
    }

    document.getElementById('messageForm').addEventListener('submit', function(event) {
      event.preventDefault();
      var message = document.getElementById('message').value;
      let datas = {
        type:"message",
        username:localStorage.getItem("username"),
        content: message
      }
      socket.send(JSON.stringify(datas))
      init.call()
    });
    init()
  </script>
</body>
</html>
